﻿using GetTogether.Studio.WebService;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class WebService_Proxy_Default : System.Web.UI.Page
{
    #region Attributes
    string ProjectName
    {
        get
        {
            return Request["pn"];
        }
    }
    string UserCode
    {
        get
        {
            return Request["user"];
        }
    }
    #endregion

    private string GetMethodName(string requestXml)
    {
        System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(@"<soap:Body><(?<MethodName>[A-Z|0-9|_]{1,})([ ]|\>)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        System.Text.RegularExpressions.Match m = regx.Match(requestXml);
        if (m.Success)
        {
            return m.Groups["MethodName"].Value;
        }
        return "";
    }
    private void WriteError(string error)
    {
        Response.Write(error);
        GetTogether.Studio.Log.Error(new Exception(error));
        Response.End();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        #region Validate
        if (string.IsNullOrEmpty(ProjectName))
        {
            WriteError("Invalid project name");
        }
        else if (string.IsNullOrEmpty(UserCode))
        {
            WriteError("Invalid user");
        }
        #endregion
        ProjectParameter parameter = ProjectParameter.GetSettingsByProjectName(UserCode, ProjectName, UserCode);
        if (parameter == null)
        {
            WriteError("Project not found");
        }
        string requestXml = GetTogether.Web.WebHelper.GetRequestInputString(this.Request);
        string methodName = GetMethodName(requestXml);
        if (!string.IsNullOrEmpty(requestXml) && requestXml.IndexOf("<soap:Body>") > 0 && string.IsNullOrEmpty(methodName))
        {
            WriteError("Method name not found");
        }
        if (!string.IsNullOrEmpty(Request["WSDL"]) || string.IsNullOrEmpty(requestXml))
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            string wsdlAddress = parameter.WsdlAddress;
            if (string.IsNullOrEmpty(wsdlAddress)) wsdlAddress = string.Concat(parameter.Address, parameter.Address.IndexOf("?") > 0 ? "&" : "?", "WSDL");
            Response.Write(wc.DownloadString(wsdlAddress));
            Response.End();
        }
        bool enableCache = false;
        if (parameter.Proxy != null) enableCache = parameter.Proxy.EnableCache;
        string responseXml = string.Empty;
        #region Proxy Case
        string proxyPath =WebServiceProxyHelper.GetProxyPath(UserCode, parameter.ProjectName, methodName);
        if (System.IO.Directory.Exists(proxyPath))
        {
            foreach (string proxyCase in System.IO.Directory.GetDirectories(proxyPath))
            {
                ProxyCaseParameter proxyParam = GetTogether.Utility.SerializationHelper.FromXml<ProxyCaseParameter>(
                    System.IO.File.ReadAllText(System.IO.Path.Combine(proxyCase, "Parameter.txt"), System.Text.Encoding.UTF8));
                if (!string.IsNullOrEmpty(proxyParam.Regular))
                {
                    System.Text.RegularExpressions.Match m = new System.Text.RegularExpressions.Regex(proxyParam.Regular, System.Text.RegularExpressions.RegexOptions.None).Match(requestXml);
                    if (m.Success)
                    {
                        responseXml= System.IO.File.ReadAllText(System.IO.Path.Combine(proxyCase, "Response.txt"), System.Text.Encoding.UTF8);
                        Response.Write(responseXml);
                        Response.End();
                    }
                }
                else if(requestXml==System.IO.File.ReadAllText(System.IO.Path.Combine(proxyCase, "Request.txt")))
                {
                    responseXml = System.IO.File.ReadAllText(System.IO.Path.Combine(proxyCase, "Response.txt"), System.Text.Encoding.UTF8);
                    Response.Write(responseXml);
                    Response.End();
                }
            }
        }
        #endregion
        string cacheKey = string.Concat("Proxy", "|", UserCode, "|", parameter.ProjectName, "|", methodName, "|", requestXml);
        if (enableCache)
        {
            responseXml = (string)GetTogether.Web.CacheHelper.GetCache(cacheKey);
            if (!string.IsNullOrEmpty(responseXml))
            {
                Response.Write(responseXml);
                Response.End();
            }
        }
        GetTogether.Studio.WebService.NormalRequest nr = new GetTogether.Studio.WebService.NormalRequest();
        nr.Url = parameter.Address;

        responseXml = nr.SendRequest(requestXml, new GetTogether.Studio.WebService.RequestProperty());
        if (enableCache)
        {
            GetTogether.Web.CacheHelper.SetCache(cacheKey, responseXml);
        }
        #region Save Proxy Log
        //string proxyPath = GetTogether.Studio.WebService.ProjectParameter.GetSettingsPath(UserCode);
        //proxyPath = System.IO.Path.Combine(proxyPath, string.Concat(parameter.ProjectName, "(Proxy)"));
        //proxyPath = System.IO.Path.Combine(proxyPath, "History");
        //if (!System.IO.Directory.Exists(proxyPath)) System.IO.Directory.CreateDirectory(proxyPath);

        #endregion
        Response.Write(responseXml);
        Response.End();
    }
}